# 图像二进制处理代码
# 下面是一个将图片转换为二进制（bytes）的通用函数，支持传入图片路径或 OpenCV/Numpy 图像数组。
import cv2
import base64
import numpy as np
from io import BytesIO
from PIL import Image
import base64
# 从图片路径读取并转二进制
def image_file_to_binary(file_path: str) -> bytes:
    """读取图片文件并转为二进制内容"""
    with open(file_path, "rb") as f:
        return f.read()
def cv2_image_to_binary(img_array) -> bytes:
    """将 OpenCV 读取的 BGR 图像数组转为 PNG 格式的二进制数据"""
    # OpenCV 是 BGR，PIL 是 RGB
    img_rgb = cv2.cvtColor(img_array, cv2.COLOR_BGR2RGB)
    pil_img = Image.fromarray(img_rgb)
    buffer = BytesIO()
    pil_img.save(buffer, format="PNG")
    return buffer.getvalue()

def binary_to_base64_image(binary_data: bytes) -> str:
    """将图片的二进制数据转换为 base64 字符串，并加上前缀方便前端展示"""
    base64_str = base64.b64encode(binary_data).decode('utf-8')
    return base64_str

def base64_to_cv2_image(base64_str: str):
    """将 base64 字符串转换为 OpenCV 图像"""
    img_bytes = base64.b64decode(base64_str)
    nparr = np.frombuffer(img_bytes, np.uint8)
    img_cv2 = cv2.imdecode(nparr, cv2.IMREAD_COLOR)
    return img_cv2

if __name__ == "__main__":
    img_cv2 = cv2.imread("im0.jpg")  # OpenCV 读取图片
    imgbinaryResult = binary_data = cv2_image_to_binary(img_cv2)
    print(len(imgbinaryResult))  # 输出二进制数据长度
    # 二进制转 base64
    base64_str = binary_to_base64_image(imgbinaryResult)
    print("Base64 Length:", len(base64_str))
    # base64 → OpenCV 图像
    recovered_img = base64_to_cv2_image(base64_str)
    # 显示图片
    cv2.imshow("Recovered Image", recovered_img)
    cv2.waitKey(0)
    cv2.destroyAllWindows()
